package com.caocaog.market.applets;

import com.caocaog.market.annotation.IgnoreAuth;
import com.caocaog.market.controller.BaseController;
import com.caocaog.market.entity.Member;
import com.caocaog.market.entity.ShopCart;
import com.caocaog.market.service.ShopCartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.Trim;
import org.jeecg.common.exception.CheckFailedException;
import org.jeecg.common.system.base.entity.groups.InsertGroup;
import org.jeecg.common.system.base.entity.groups.SelectGroup;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 小程序购物车
 *
 * @author chechen
 * @date 2022-04-06
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(value = "memberCart", tags = "小程序购物车")
@RequestMapping("/api/shoppingCart")
public class ShopCartController extends BaseController {

    private final ShopCartService shopCartService;

    @Trim
    @IgnoreAuth
    @ApiOperation(value = "我的购物车", response = ShopCart.class)
    @PostMapping(value = "/my")
    public Result<List<ShopCart>> myShoppingCart(@RequestBody @Validated({SelectGroup.class}) ShopCart shopCart) {
        log.info("查询我的购物车");
        return Result.OK(this.shopCartService.myShopCart(shopCart.getMemberId(), shopCart.getShopId()));
    }

    @Trim
    @IgnoreAuth
    @ApiOperation(value = "添加购物车", response = ShopCart.class)
    @PostMapping(value = "/operate")
    public Result<List<ShopCart>> operate(@RequestBody @Validated({InsertGroup.class}) ShopCart shopCart) {
        log.info("添加购物车");
        shopCart.clearFields();
        List<ShopCart> shopCarts = this.shopCartService.operateShopCart(shopCart);
        return Result.OK(shopCarts);
    }

    @Trim
    @AutoLog(value = "清空购物车")
    @ApiOperation(value = "清空购物车", response = List.class)
    @DeleteMapping(value = "/clean")
    public Result<List<ShopCart>> clean(@RequestBody @Validated({SelectGroup.class}) ShopCart shopCart) {
        log.info("清空购物车");
        Member member = verifyUserForApp();
        if (!member.getId().equals(shopCart.getMemberId())) {
            throw new CheckFailedException("非当前登陆用户操作");
        }
        return Result.OK(this.shopCartService.cleanShopCart(shopCart.getMemberId(), shopCart.getShopId()));

    }

    @IgnoreAuth
    @ApiOperation(value = "清除购物车缓存", response = List.class)
    @DeleteMapping(value = "/cleanCache")
    public Result<Long> cleanCache(@RequestParam(required = false) String shopId) {
        log.info("清除购物车缓存");
        return Result.OK(this.shopCartService.cleanCacheShopCart(shopId));
    }

}
